var con = require('dao/dbConnect');

/**
 * 插入多条记录
 * col为空时,需要parm传入所有字段的值
 * @param {*} table 数据库表
 * @param {*} col [表字段1,表字段2] 可传空
 * @param {*} parm 需要插入的值  形如[[值1,值2],[值1,值2],[值1,值2]]
 */
function insertOjbs(table, col, parm){
    var sql = "insert into " + table;
    var parmAll = [];
    if(col!=null && col.length>0){
        var colSql = " ( ";
        for(var i=0;i<col.length;i++) {
            colSql += col[i] + " ,";
        }
        colSql = colSql.substring(0,colSql.length-1);
        colSql += " ) ";
        sql += colSql;
    }
    sql += " values ";
    if(parm!=null && parm.length>0){
        var parmObjLength = parm[0].length;
        //验证参数个数是否一致
        for(j in parm){
            if(parmObjLength != parm[j].length){
                //返回错误,参数组长度不一致问题
            }
        }
        var parms = " ( ";
        for(var k=0;k<parmObjLength;k++){
            parms += " ?,";
        }
        parms = parms.substring(0, parms.length-1);
        parms += ")";
        var parmObjs = "";
        for(i in parm){
            parmObjs += parms + ",";
        }
        parmObjs = parmObjs.substring(0,parmObjs.length-1);
        sql += parmObjs;
        //sql = insert into table(col1,col2) values (?,?),(?,?)
        console.log(sql);
        for(j in parm){
            for(k in parm[j]){
                parmAll.push(parm[j][k]);
            }
        }
    } else {
        //insert没有参数,返回错误
    }
    client = con.connect();
    client.query(sql, parmAll, function(err, results, fields){
        return results;
    });
}

exports.insertOjbs = insertOjbs;